package com.health.mapp.service;

import com.health.db.dto.StuffDetailDto;
import com.health.db.model.UserLIST;
import com.health.db.service.user.IStuffListService;
import com.health.db.service.user.IUserLISTService;
import com.health.mapp.bean.GetStuffOpenIdResp;
import com.health.mapp.utils.ResultCode;
import com.wxtools.api.IService;
import com.wxtools.bean.result.WxOAuth2AccessTokenResult;
import net.sf.json.JSONObject;
import org.apache.http.util.TextUtils;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class GetStuffOpenId extends HttpServlet{

    private IService mpService;
    private IStuffListService stuffListService;
    private IUserLISTService userLISTService;
    private static Logger logger = Logger.getLogger(GetStuffOpenId.class);

    public void init(ServletConfig config) throws ServletException {
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
                config.getServletContext());
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ServletContext servletContext = request.getSession().getServletContext();
        ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        mpService = (IService) applicationContext.getBean("mpService");
        stuffListService = (IStuffListService) applicationContext.getBean("stuffListService");
        userLISTService=(IUserLISTService)applicationContext.getBean("userLISTService");

        GetStuffOpenIdResp _resp = new GetStuffOpenIdResp();
        String code = request.getParameter("code");



        if (TextUtils.isEmpty(code))
        {
            _resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_ERROR);
            _resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_ERROR_NOTE);
        }else
        {
            try {
                WxOAuth2AccessTokenResult tokenResult=mpService.oauth2ToGetAccessToken(code);
                List<UserLIST> userLISTS=userLISTService.selectByWXOpenid(tokenResult.getOpenid());

                if (null!=userLISTS)
                {
                    for (UserLIST userLIST:userLISTS)
                    {
                        if (userLIST.getTypeid()==2||userLIST.getTypeid()==3)
                        {
                            userLIST.setPassword(null);
                            _resp.setUserLIST(userLIST);
                        }
                    }
                }

                if (null==_resp.getUserLIST())
                {
                    _resp.setTokenResult(tokenResult);
                }


            }catch (Exception e)
            {
                logger.error(e.getMessage());
                _resp.setErrorCode(-1);
                _resp.setErrorMsg("code error");
                logger.info("code error");
            }
        }

        String callbackName = request.getParameter("jsonpCallback");// 客户端请求参数
        String jsonStr = JSONObject.fromObject(_resp).toString();
        String renderStr = callbackName+"("+jsonStr+")";
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers", "cache-control,content-type,hash-referer,x-requested-with");
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.print(renderStr);
        out.println("\r\n");
        out.flush();
        out.close();

    }
}
